// LineChart.js
// LineChart.js
import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { TooltipComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册所需的组件
echarts.use([LineChart, TooltipComponent, GridComponent, CanvasRenderer]);

const LineChartComponent = ({ data, options = {} }) => {
    const chartRef = useRef(null);

    useEffect(() => {
        if (!chartRef.current) return;

        // 初始化图表实例
        const chartInstance = echarts.init(chartRef.current);

        // 默认配置
        const defaultOption = {
            grid: {
                left: '5%',       // 左边距
                right: '5%',      // 右边距
                top: '10%',       // 上边距
                bottom: '10%',    // 下边距
                containLabel: true,
                // borderColor: "#282f47",
                // show: true,
            },

            tooltip: {
                trigger: 'axis', // 触发类型，'axis' 表示按坐标轴触发
                axisPointer: {
                    type: 'line', // 默认为直线，可选为：'line' | 'shadow'
                    lineStyle: {
                        color: '#333', // 指示线的颜色
                        width: 1,      // 指示线的宽度
                    },
                },
            },

            xAxis: {
                type: "category",
                boundaryGap: false,
                data: data.names,
                axisLabel: {
                    margin: 15,//距离
                    interval: 0,
                    rotate: 45,//倾斜度
                },
                triggerEvent: true
            },
            yAxis: {
                type: "value",
            },
            series: [
                {
                    data: data.values,
                    type: "line",
                    areaStyle: {},
                },
            ],
        };

        // 合并用户传入的自定义配置
        const finalOption = { ...defaultOption, ...options };

        // 设置图表配置
        chartInstance.setOption(finalOption);

        // 监听窗口尺寸变化，自动调整图表大小
        window.addEventListener('resize', () => {
            chartInstance.resize();
        });

        // 组件卸载时销毁图表实例
        return () => {
            window.removeEventListener('resize', () => {
                chartInstance.resize();
            });
            chartInstance.dispose();
        };
    }, [data, options]);

    return <div ref={chartRef} style={{ width: '100%', height: '400px' }} />;
};

export default LineChartComponent;